import React, { Component } from 'react'
import {
  Text,
  View,
  Alert,
  StyleSheet,
  FlatList,
  DeviceEventEmitter,
  TouchableOpacity,
} from 'react-native'

import Icon from 'react-native-vector-icons/Ionicons'
import Item from '../component/Item'
import Button from '../component/Button'
import RootView from '../component/RootView'
import CheckBox from '../component/CheckBox'
import Base from './Base'
import { NavigationActions, px2dp } from '../utils'
import * as addressService from '../services/address'

class Address extends Base {
  constructor(props) {
    super(props)
    this.state = {
      selectable: 0,
      records: [],
    }
  }
  static navigationOptions = {
    title: '收货地址',
    headerBackTitle: null,
    headerTitleStyle: {
      alignSelf: 'center',
    },
    headerStyle: {
      backgroundColor: 'white',
      borderBottomWidth: 0,
      shadowColor: 'transparent',
      elevation: 1,
    },
    headerRight: <View />,
  }
  loadData() {
    this.setState({ fetching: true })
    addressService
      .list()
      .then(data => {
        this.setState({
          fetching: false,
          records: data.records,
        })
      })
      .catch(e => {
        this.checkError(e)
      })
  }
  onDefault = id => {
    this.setState({ fetching: true })
    addressService
      .setDefault({ id })
      .then(data => {
        this.loadData()
      })
      .catch(e => {
        this.checkError(e)
      })
  }
  onEdit = addressId => {
    this.goto('EditAddress', {
      key: this.props.navigation.state.key,
      addressId,
    })
  }
  onRemove = id => {
    Alert.alert(
      '确定删除该地址？',
      null,
      [
        { text: '取消', style: 'cancel' },
        { text: '确定', onPress: () => this.removeAddress(id) },
      ],
      { cancelable: true }
    )
  }
  removeAddress = id => {
    this.setState({ fetching: true })
    addressService
      .remove({ id })
      .then(data => {
        this.loadData()
      })
      .catch(e => {
        this.checkError(e)
      })
  }
  onSelect = addressId => {
    const { key, selectable } = this.props.navigation.state.params

    if (!selectable) {
      return
    }
    // 返回
    this.setParams(key, { addressId })
    setTimeout(() => {
      this.goBack()
    }, 50)
  }
  onModalClose = () => {
    this.setState({ msg: null })
  }
  componentWillReceiveProps(nextProps) {
    if (
      nextProps.navigation.state.params &&
      nextProps.navigation.state.params.reload
    ) {
      this.loadData()
    }
  }
  componentDidMount() {
    this.loadData()
  }
  renderItem({ item, index }) {
    const { key } = this.props.navigation.state

    let top = 0
    if (index == 0) {
      top = 10
    }
    return (
      <Button
        key={index}
        style={{ marginTop: 10 }}
        onPress={() => this.onSelect(item.id)}
      >
        <View>
          <View style={styles.address}>
            <Text style={{ color: '#333' }}>
              {`${item.name} ${item.phone}`}
            </Text>
            <View style={styles.ads1List}>
              <Text style={{ color: '#333' }}>
                {item.village}
                {item.address}
              </Text>
            </View>
          </View>
          <View style={styles.action}>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
              }}
            >
              <CheckBox
                checked={!!item.isDefault}
                color="#e23f3c"
                onPress={() => {
                  if (!item.isDefault) {
                    this.onDefault(item.id)
                  }
                }}
              />
              <Text style={{ color: '#666', fontSize: 10, marginLeft: 5 }}>
                {item.isDefault ? '默认地址' : '设为默认'}
              </Text>
            </View>
            <View style={{ flexDirection: 'row' }}>
              <TouchableOpacity onPress={() => this.onRemove(item.id)}>
                <Text style={{ color: '#333', fontSize: 12 }}>删除</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={{ marginLeft: 15 }}
                onPress={() => this.onEdit(item.id)}
              >
                <Text style={{ color: '#333', fontSize: 12 }}>编辑</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Button>
    )
  }
  render() {
    const { fetching, records } = this.state
    const currentKey = this.props.navigation.state.key
    const { selectable, key } = this.props.navigation.state.params

    return (
      <RootView
        fetching={fetching}
        onModalClose={() => this.onModalClose()}
        style={styles.container}
      >
        <FlatList
          data={records}
          keyExtractor={(item, index) => String(index)}
          renderItem={({ item, index }) => this.renderItem({ item, index })}
        />
        <Button
          style={{
            height: px2dp(45),
          }}
          onPress={() => {
            // 如果是从订单提交界面过来的，新增或修改地址后，直接跳回订单确认界面
            this.goto('EditAddress', {
              key: currentKey,
              parentKey: key,
              selectable,
              addressId: 0,
            })
          }}
        >
          <View
            style={{
              flexDirection: 'row',
              backgroundColor: '#fff',
              flex: 1,
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            <Icon name="ios-add-circle-outline" size={18} color="#0096ff" />
            <Text style={{ color: '#0096ff', marginLeft: 8 }}>{'新增地址'}</Text>
          </View>
        </Button>
      </RootView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  address: {
    borderBottomWidth: 1,
    borderBottomColor: '#fbfbfb',
    paddingHorizontal: 16,
    backgroundColor: '#fff',
    paddingVertical: 8,
  },
  action: {
    alignItems: 'center',
    justifyContent: 'space-between',
    flexDirection: 'row',
    borderBottomWidth: 1,
    borderBottomColor: '#fbfbfb',
    paddingHorizontal: 16,
    backgroundColor: '#fff',
    paddingVertical: 8,
  },
  tag: {
    color: '#fff',
    minWidth: px2dp(30),
    textAlign: 'center',
    paddingVertical: 1,
    paddingHorizontal: 2,
    borderRadius: 5,
    marginRight: 5,
  },
  ads1List: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingTop: 5,
  },
})

export default Address
